//
// Created by zx208 on 2024/10/27.
//

#include "SequenceStack.h"

Status InitStack(SqStack *S){
    S->base = (ElemType *) malloc(sizeof( ElemType) * MAXSTACK);
    if(!S->base) exit(OVERFLOW);
    S->top = S->base; // 栈顶指向栈底
    S->stacksize = MAXSTACK; // 栈的容量
    return OK;
}

//1.判断是否栈满，若满则出错（上溢）
//2.元素e压入栈顶
//3.栈顶指针+1
Status Push_SS(SqStack *S, ElemType e){
    // 如果栈已满 要么报错 返回ERROR 要么自己分配更大的空间
    // S->base = (ElemType *) realloc(sizeof( ElemType) * (MAXSTACK + STACKINCREMENT))
    // 其中STACKINCREMENT 就是自己定义扩增的容量
    if(S->top - S->base == S->stacksize) return ERROR;
    *(S->top++) = e; // 相当于先 *S.top = e; 再 S.top++;
    return OK;
}


//1.判断是否栈空，若空则出错（下溢）
//2.栈顶指针-1
//3.获取栈顶元素e
Status Pop_SS(SqStack *S, ElemType *e){
    // 栈空
    if(S->base == S->top) return ERROR;
    *e = *(--S->top);
    return OK;
}

Status IsEmpty_SS(SqStack *S) {
    return S->top == S->base;
}

Status IsFull_SS(SqStack *S) {
    return S->top - S->base == S->stacksize;
}

ElemType GetTop_SS(SqStack *S) {
    if (!IsEmpty_SS(S)) return *(S->top - 1);
    else exit(OVERFLOW);
}

int StackLength_SS(SqStack S) {
    return S.top - S.base;
}

int main(void){
    SqStack S;
    InitStack(&S);
    Push_SS(&S, 1);
    Push_SS(&S, 2);
    Push_SS(&S, 3);
    Push_SS(&S, 4);
    while (!IsEmpty_SS(&S))
    {
        ElemType e;
        Pop_SS(&S, &e);
        printf("%d ", e);
    }
    return 0;
}